package com.fengwk.support.code;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;

import com.fengwk.support.util.LoggerUtils;
import com.fengwk.support.util.LoggerUtils.Logger;

/**
 * 雪花算法
 * 
 * @author fengwk
 *
 */
public class Snowflake implements Serializable {

	private static final long serialVersionUID = -2396770821040471805L;

	private static final Logger LOG = LoggerUtils.getLogger(Snowflake.class);

	private final long workerId;
	private final long datacenterId;
	private final AtomicLong sequence = new AtomicLong(0L);
	
	private long twepoch;// 不允许改动

	private final long workerIdBits = 5L;
	private final long datacenterIdBits = 5L;
	private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
	private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
	private final long sequenceBits = 12L;

	private final long workerIdShift = sequenceBits;
	private final long datacenterIdShift = sequenceBits + workerIdBits;
	private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
	private final long sequenceMask = -1L ^ (-1L << sequenceBits);

	private final AtomicLong lastTimestamp = new AtomicLong(-1L);
	
	/**
	 * @param workerId 0-32
	 * @param datacenterId 0-32
	 * @param twepoch 指定的开始时间
	 */
	public Snowflake(final long workerId, final long datacenterId, final long twepoch) {
		// sanity check for workerId
		if (workerId > maxWorkerId || workerId < 0) {
			throw new IllegalArgumentException(
					String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
		}
		if (datacenterId > maxDatacenterId || datacenterId < 0) {
			throw new IllegalArgumentException(
					String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
		}
		this.workerId = workerId;
		this.datacenterId = datacenterId;
		this.twepoch = twepoch;
	}

	public synchronized long nextId() {
		long timestamp = timeGen();

		if (timestamp < lastTimestamp.get()) {
		    LOG.error(String.format("clock is moving backwards.  Rejecting requests until %d.", lastTimestamp));
			throw new RuntimeException(String.format(
					"Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp.get() - timestamp));
		}

		if (lastTimestamp.get() == timestamp) {
			sequence.set(sequence.addAndGet(1L) & sequenceMask);
			if (sequence.get() == 0) {
				timestamp = tilNextMillis(lastTimestamp.get());
			}
		} else {
			sequence.set(0L);
		}

		lastTimestamp.set(timestamp);

		return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift)
				| (workerId << workerIdShift) | sequence.get();
	}

	protected long tilNextMillis(long lastTimestamp) {
		long timestamp = timeGen();
		while (timestamp <= lastTimestamp) {
			timestamp = timeGen();
		}
		return timestamp;
	}

	protected long timeGen() {
		return System.currentTimeMillis();
	}
	
}
